package second.binarytree;


public class Solution18 {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return getTree(inorder, postorder, 0, inorder.length - 1, 0, postorder.length - 1);
    }

    public TreeNode getTree(int[] inorder, int[] postorder, int inStart, int inEnd, int postStart, int postEnd) {
        if (inStart > inEnd || postStart > postEnd) return null;
        TreeNode root = new TreeNode(postorder[postEnd]);
        if (inStart == inEnd) return root;
        int index = fingIndex(inorder, root.val, inStart, inEnd);
        root.left = getTree(inorder, postorder, inStart, index - 1, postStart, postStart + index - inStart - 1);
        root.right = getTree(inorder, postorder, index + 1, inEnd, postStart + index -inStart, postEnd - 1);
        return root;
    }

    public int fingIndex(int[] nums, int target, int start, int end) {
        for (int i = start; i <= end; i++) {
            if (target == nums[i]) return i;
        }
        return -1;
    }
}

